9313ccd37c56e9ee6c6c978e9f36fb06e68c90b6
3 * Database load balancing interface
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
22 * @author Aaron Schulz
26 * Interface for database load balancing object that manages IDatabase handles
28 * @todo: loosen up DB classes from MWException
32 interface ILoadBalancer
{
34 * @param array $params Array with keys:
35 * - servers : Required. Array of server info structures.
36 * - loadMonitor : Name of a class used to fetch server lag and load.
37 * - readOnlyReason : Reason the master DB is read-only if so [optional]
38 * - waitTimeout : Maximum time to wait for replicas for consistency [optional]
39 * - srvCache : BagOStuff object [optional]
40 * - wanCache : WANObjectCache object [optional]
43 public function __construct( array $params );
46 * Get the index of the reader connection, which may be a replica DB
47 * This takes into account load ratios and lag times. It should
48 * always return a consistent index during a given invocation
50 * Side effect: opens connections to databases
51 * @param string|bool $group Query group, or false for the generic reader
52 * @param string|bool $wiki Wiki ID, or false for the current wiki
54 * @return bool|int|string
56 public function getReaderIndex( $group = false, $wiki = false );
59 * Set the master wait position
60 * If a DB_REPLICA connection has been opened already, waits
61 * Otherwise sets a variable telling it to wait if such a connection is opened
62 * @param DBMasterPos $pos
64 public function waitFor( $pos );
67 * Set the master wait position and wait for a "generic" replica DB to catch up to it
69 * This can be used a faster proxy for waitForAll()
71 * @param DBMasterPos $pos
72 * @param int $timeout Max seconds to wait; default is mWaitTimeout
73 * @return bool Success (able to connect and no timeouts reached)
75 public function waitForOne( $pos, $timeout = null );
78 * Set the master wait position and wait for ALL replica DBs to catch up to it
79 * @param DBMasterPos $pos
80 * @param int $timeout Max seconds to wait; default is mWaitTimeout
81 * @return bool Success (able to connect and no timeouts reached)
83 public function waitForAll( $pos, $timeout = null );
86 * Get any open connection to a given server index, local or foreign
87 * Returns false if there is no connection open
89 * @param int $i Server index
90 * @return IDatabase|bool False on failure
92 public function getAnyOpenConnection( $i );
95 * Get a connection by index
96 * This is the main entry point for this class.
98 * @param int $i Server index
99 * @param array|string|bool $groups Query group(s), or false for the generic reader
100 * @param string|bool $wiki Wiki ID, or false for the current wiki
102 * @throws MWException
105 public function getConnection( $i, $groups = [], $wiki = false );
108 * Mark a foreign connection as being available for reuse under a different
109 * DB name or prefix. This mechanism is reference-counted, and must be called
110 * the same number of times as getConnection() to work.
112 * @param IDatabase $conn
113 * @throws MWException
115 public function reuseConnection( $conn );
118 * Get a database connection handle reference
120 * The handle's methods wrap simply wrap those of a IDatabase handle
122 * @see LoadBalancer::getConnection() for parameter information
125 * @param array|string|bool $groups Query group(s), or false for the generic reader
126 * @param string|bool $wiki Wiki ID, or false for the current wiki
129 public function getConnectionRef( $db, $groups = [], $wiki = false );
132 * Get a database connection handle reference without connecting yet
134 * The handle's methods wrap simply wrap those of a IDatabase handle
136 * @see LoadBalancer::getConnection() for parameter information
139 * @param array|string|bool $groups Query group(s), or false for the generic reader
140 * @param string|bool $wiki Wiki ID, or false for the current wiki
143 public function getLazyConnectionRef( $db, $groups = [], $wiki = false );
146 * Open a connection to the server given by the specified index
147 * Index must be an actual index into the array.
148 * If the server is already open, returns it.
150 * On error, returns false, and the connection which caused the
151 * error will be available via $this->mErrorConnection.
153 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
155 * @param int $i Server index
156 * @param string|bool $wiki Wiki ID, or false for the current wiki
157 * @return IDatabase|bool Returns false on errors
159 public function openConnection( $i, $wiki = false );
164 public function getWriterIndex();
167 * Returns true if the specified index is a valid server index
172 public function haveIndex( $i );
175 * Returns true if the specified index is valid and has non-zero load
180 public function isNonZeroLoad( $i );
183 * Get the number of defined servers (not the number of open connections)
187 public function getServerCount();
190 * Get the host name or IP address of the server with the specified index
191 * Prefer a readable name if available.
195 public function getServerName( $i );
198 * Return the server info structure for a given index, or false if the index is invalid.
202 public function getServerInfo( $i );
205 * Sets the server info structure for the given index. Entry at index $i
206 * is created if it doesn't exist
208 * @param array $serverInfo
210 public function setServerInfo( $i, array $serverInfo );
213 * Get the current master position for chronology control purposes
214 * @return DBMasterPos|bool Returns false if not applicable
216 public function getMasterPos();
219 * Disable this load balancer. All connections are closed, and any attempt to
220 * open a new connection will result in a DBAccessError.
222 public function disable();
225 * Close all open connections
227 public function closeAll();
232 * Using this function makes sure the LoadBalancer knows the connection is closed.
233 * If you use $conn->close() directly, the load balancer won't update its state.
235 * @param IDatabase $conn
237 public function closeConnection( IDatabase
$conn );
240 * Commit transactions on all open connections
241 * @param string $fname Caller name
242 * @throws DBExpectedError
244 public function commitAll( $fname = __METHOD__
);
247 * Perform all pre-commit callbacks that remain part of the atomic transactions
248 * and disable any post-commit callbacks until runMasterPostTrxCallbacks()
250 * Use this only for mutli-database commits
252 public function finalizeMasterChanges();
255 * Perform all pre-commit checks for things like replication safety
257 * Use this only for mutli-database commits
259 * @param array $options Includes:
260 * - maxWriteDuration : max write query duration time in seconds
261 * @throws DBTransactionError
263 public function approveMasterChanges( array $options );
266 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
268 * The DBO_TRX setting will be reverted to the default in each of these methods:
269 * - commitMasterChanges()
270 * - rollbackMasterChanges()
272 * This allows for custom transaction rounds from any outer transaction scope.
274 * @param string $fname
275 * @throws DBExpectedError
277 public function beginMasterChanges( $fname = __METHOD__
);
280 * Issue COMMIT on all master connections where writes where done
281 * @param string $fname Caller name
282 * @throws DBExpectedError
284 public function commitMasterChanges( $fname = __METHOD__
);
287 * Issue all pending post-COMMIT/ROLLBACK callbacks
289 * Use this only for mutli-database commits
291 * @param integer $type IDatabase::TRIGGER_* constant
292 * @return Exception|null The first exception or null if there were none
294 public function runMasterPostTrxCallbacks( $type );
297 * Issue ROLLBACK only on master, only if queries were done on connection
298 * @param string $fname Caller name
299 * @throws DBExpectedError
301 public function rollbackMasterChanges( $fname = __METHOD__
);
304 * Suppress all pending post-COMMIT/ROLLBACK callbacks
306 * Use this only for mutli-database commits
308 * @return Exception|null The first exception or null if there were none
310 public function suppressTransactionEndCallbacks();
313 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
315 * @param string $fname Caller name
317 public function flushReplicaSnapshots( $fname = __METHOD__
);
320 * @return bool Whether a master connection is already open
322 public function hasMasterConnection();
325 * Determine if there are pending changes in a transaction by this thread
328 public function hasMasterChanges();
331 * Get the timestamp of the latest write query done by this thread
332 * @return float|bool UNIX timestamp or false
334 public function lastMasterChangeTimestamp();
337 * Check if this load balancer object had any recent or still
338 * pending writes issued against it by this PHP thread
340 * @param float $age How many seconds ago is "recent" [defaults to mWaitTimeout]
343 public function hasOrMadeRecentMasterChanges( $age = null );
346 * Get the list of callers that have pending master changes
348 * @return string[] List of method names
350 public function pendingMasterChangeCallers();
353 * @note This method will trigger a DB connection if not yet done
354 * @param string|bool $wiki Wiki ID, or false for the current wiki
355 * @return bool Whether the generic connection for reads is highly "lagged"
357 public function getLaggedReplicaMode( $wiki = false );
360 * @note This method will never cause a new DB connection
361 * @return bool Whether any generic connection used for reads was highly "lagged"
363 public function laggedReplicaUsed();
366 * @note This method may trigger a DB connection if not yet done
367 * @param string|bool $wiki Wiki ID, or false for the current wiki
368 * @param IDatabase|null DB master connection; used to avoid loops [optional]
369 * @return string|bool Reason the master is read-only or false if it is not
371 public function getReadOnlyReason( $wiki = false, IDatabase
$conn = null );
374 * Disables/enables lag checks
375 * @param null|bool $mode
378 public function allowLagged( $mode = null );
383 public function pingAll();
386 * Call a function with each open connection object
387 * @param callable $callback
388 * @param array $params
390 public function forEachOpenConnection( $callback, array $params = [] );
393 * Call a function with each open connection object to a master
394 * @param callable $callback
395 * @param array $params
397 public function forEachOpenMasterConnection( $callback, array $params = [] );
400 * Call a function with each open replica DB connection object
401 * @param callable $callback
402 * @param array $params
404 public function forEachOpenReplicaConnection( $callback, array $params = [] );
407 * Get the hostname and lag time of the most-lagged replica DB
409 * This is useful for maintenance scripts that need to throttle their updates.
410 * May attempt to open connections to replica DBs on the default DB. If there is
411 * no lag, the maximum lag will be reported as -1.
413 * @param bool|string $wiki Wiki ID, or false for the default database
414 * @return array ( host, max lag, index of max lagged host )
416 public function getMaxLag( $wiki = false );
419 * Get an estimate of replication lag (in seconds) for each server
421 * Results are cached for a short time in memcached/process cache
423 * Values may be "false" if replication is too broken to estimate
425 * @param string|bool $wiki
426 * @return int[] Map of (server index => float|int|bool)
428 public function getLagTimes( $wiki = false );
431 * Get the lag in seconds for a given connection, or zero if this load
432 * balancer does not have replication enabled.
434 * This should be used in preference to Database::getLag() in cases where
435 * replication may not be in use, since there is no way to determine if
436 * replication is in use at the connection level without running
437 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
438 * function instead of Database::getLag() avoids a fatal error in this
439 * case on many installations.
441 * @param IDatabase $conn
442 * @return int|bool Returns false on error
444 public function safeGetLag( IDatabase
$conn );
447 * Wait for a replica DB to reach a specified master position
449 * This will connect to the master to get an accurate position if $pos is not given
451 * @param IDatabase $conn Replica DB
452 * @param DBMasterPos|bool $pos Master position; default: current position
453 * @param integer|null $timeout Timeout in seconds [optional]
454 * @return bool Success
456 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = null );
459 * Clear the cache for slag lag delay times
461 * This is only used for testing
463 public function clearLagTimeCache();
466 * Set a callback via IDatabase::setTransactionListener() on
467 * all current and future master connections of this load balancer
469 * @param string $name Callback name
470 * @param callable|null $callback
472 public function setTransactionListener( $name, callable
$callback = null );